package com.yupi.springbootinit.pulldata;

import cn.hutool.core.lang.Console;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class PostPull {


    @Resource
    private PostService postService;

    /**
     * 测试爬取网站数据
     */
    @Test
    public void pullData(){
        String url = "https://api.code-nav.cn/api/post/list/page/vo";
        String json = "{\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"reviewStatus\":1,\"current\":1,\"hiddenContent\":true,\"queryType\":\"hot\"}";
        String result2 = HttpRequest.post(url)
                .body(json)
                .execute().body();

        Map<String,Object> map = JSONUtil.toBean(result2, Map.class);
        JSONObject dataObject = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) dataObject.get("records");
        List<Post> posts = new ArrayList<>();
        for (Object record : records) {
            JSONObject post = (JSONObject) record;
            Post p = new Post();
            p.setTitle((String) post.get("title"));
            p.setContent((String) post.get("content"));
            p.setTags((String) post.get("tags"));
            p.setThumbNum((Integer) post.get("thumbNum"));
            p.setFavourNum((Integer) post.get("favourNum"));
            posts.add(p);
        }

        postService.saveBatch(posts);

    }
}
